﻿using KingsSharp.Common;
using KingsSharp.Common.Extensions;
using KingsSharp.Common.Filter;
using KingsSharp.Core.Data.Entity;
using KingsSharp.Core.Data.Extensions;
using KingsSharp.Web.Mvc.Binders;
using KingsSharp.Web.UI;
using CRM.Admin.Contracts.Contract.Sys;
using CRM.Admin.Contracts.Dto.Sys;
using CRM.Admin.Contracts.Model.Sys;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;


namespace CRM.Admin.Areas.Sys.Controllers
{
    public class RoleController : Controller
    {
        /// <summary>
        /// 组织机构业务契约
        /// </summary>
        public IOrganizationService _organizationService { get; set; }

        /// <summary>
        /// 角色业务契约
        /// </summary>
        public IRoleService _roleService { get; set; }

        #region 视图功能
        public ActionResult RoleIndex()
        {
            //var zTree = GetOrganizationTree();

            //return View((object)zTree.ToJsonString(true));

            return View();
        }
        public ActionResult RoleAdd()
        {
            return View();
        }
        public ActionResult RoleEdit(Guid RoleId)
        {
            var dto = _roleService.ItemRole.Where(a => a.IsDeleted == false && a.Id == RoleId).FirstOrDefault().MapTo<RoleDto>();
            return View(dto);
        }
        /// <summary>
        /// 选择角色
        /// </summary>
        /// <param name="RoleIds"></param>
        /// <returns></returns>
        public ActionResult RoleCheck(string RoleIds="")
        {
            return View(RoleIds);
        }
        #endregion

        #region 数据功能
        [HttpPost]
        public ActionResult RoleInsert([ModelBinder(typeof(JsonBinder<RoleDto>))] RoleDto dtos)
        {
            dtos.CheckNotNull("dtos");
            dtos.Id = Guid.NewGuid();
            var result = _roleService.InsertRole(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "角色“{0}”添加成功。".FormatWith(dtos.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        [HttpPost]
        public ActionResult RoleUpdate([ModelBinder(typeof(JsonBinder<RoleDto>))] RoleDto dtos)
        {
            dtos.CheckNotNull("dtos");
            var result = _roleService.UpdateRole(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "角色“{0}”更新成功。".FormatWith(dtos.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult RoleDelete(Guid RoleId, string RoleName)
        {
            RoleId.CheckNotEmpty("RoleId");
            var result = _roleService.DeleteRole(RoleId);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "角色“{0}”删除成功。".FormatWith(RoleName);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        [HttpPost]
        public ActionResult GetRoleGridData()
        {
            GridRequest request = new GridRequest(Request);
            Expression<Func<Role, bool>> predicate = FilterHelper.GetExpression<Role>(request.FilterGroup);
            int total;
            var data = _roleService.ItemRole
                .Where<Role, Guid>(predicate, request.PageCondition, out total)
                .Where(a => a.IsDeleted == false)
                .ToList();
            return Json(new GridData<object>(data.MapToList<Role, RoleDto>(), total), JsonRequestBehavior.AllowGet);
        }
        public ICollection<ZTreeNode> GetOrganizationTree()
        {
            var data = _organizationService.ItemOrganization.Include(a => a.Children)
                .Where(a => a.IsDeleted == false).OrderBy(a => a.Order).ToList();
            var zTree = data.RenderTree<Organization, ZTreeNode>(data.Where(a => a.Parent == null).ToList(), (catalog, level) =>
            {
                return new ZTreeNode()
                {
                    Id = catalog.Id.ToString(),
                    Name = catalog.Name,
                    Order = catalog.Order,
                    Pid = catalog.ParentOrganizationId.ToString(),
                    Open = level < 2
                };
            }, (catalog, sources) =>
            {
                return sources.Where(a => a.Parent != null
                    && a.Parent.Id == catalog.Id).ToList();
            }, (parentNode, newNode) =>
            {
                if (parentNode.Children == null)
                {
                    parentNode.Children = new List<ZTreeNode>();
                }
                parentNode.Children.Add(newNode);
            });
            return zTree;
        }
        #endregion
    }
}